import axios from "axios";
import {Message} from 'element-ui'
import router from "@/router";

const request = axios.create({
    baseURL: 'http://localhost',
    timeout: 0
})


// 请求拦截
request.interceptors.request.use(config => {
    // config 请求的信息
    // 设置token start
    let accessToken = localStorage.getItem('token');
    if (accessToken && accessToken !== '') {
        config.headers.common['Authorization'] = accessToken;
    }
    return config // 将配置完成的config对象返回出去 如果不返回 请求则不会进行
}, err => {
    // 请求发生错误时的处理 抛出错误
    Promise.reject(err)
})
//响应拦截
request.interceptors.response.use(res => {
    // 我们一般在这里处理，请求成功后的错误状态码 例如状态码是500，404，403
    // res 是所有相应的信息
    // 设置token start
    // 回设置token start
    let accessToken = res.headers['Authorization'];
    if (accessToken && accessToken !== '') {
        localStorage.setItem('token', accessToken);
    }
    if (res.data.code !== 200) {
        Message({
            type: 'error',
            message: res.data.message,
            showClose: true,
        })
        return Promise.reject(res)
    }
    return Promise.resolve(res)
}, err => {
    console.log(err.response)
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.response.message = `错误请求`;
                break;
            case 401:
                err.response.message = `未授权，请重新登录`;
                Message.error(err.response.message)
                router.replace('/login')
                break;
            case 403:
                err.response.message = `拒绝访问`;
                break;
            case 404:
                err.response.message = `请求错误,未找到该资源`;
                break;
            case 405:
                err.response.message = `请求方法未允许`;
                break;
            case 408:
                err.response.message = `请求超时`;
                break;
            case 500:
                err.response.message = `服务器端出错`;
                break;
            case 501:
                err.response.message = `网络未实现`;
                break;
            case 502:
                err.response.message = `网络错误`;
                break;
            case 503:
                err.response.message = `服务不可用`;
                break;
            case 504:
                err.response.message = `网络超时`;
                break;
            case 505:
                err.response.message = `http版本不支持该请求`;
                break;
            default:
                err.response.message = `未知错误${error.response.status}`;
        }
    } else {
        error.response.message = "连接到服务器失败";
    }
    Message({
        type: 'error',
        message: err.response.message,
        showClose: true,
    })
    // 服务器响应发生错误时的处理
    Promise.reject(err)
})
export default request;